﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.Data;
using AutoMapper;

namespace Data {
    public class PhieuNhapRepository {
        public string CreateMaPhieuNhap() {
            //giay gia tri index ra
            QuanLyNhaSachEntities context = new QuanLyNhaSachEntities();
            //indentify ID
            var maxID = (from max in context.GetIndentity("PHIEUNHAP")
                        select max.CurrentIndentity).FirstOrDefault();            
            if (maxID == 1)
                maxID = 0;

            return "PN" + (maxID + 1);
        }

        /// <summary>
        /// kết quả trả về là ID của phiếu nhập vừa insert 
        /// </summary>
        /// <param name="phieuNhap">phieunhap dto</param>
        /// <returns></returns>
        public int InsertPhieuNhap(PhieuNhapDTO phieuNhap) {
            try {
                QuanLyNhaSachEntities context = new QuanLyNhaSachEntities();
                PHIEUNHAP phieuEF = new PHIEUNHAP();
                Mapper.CreateMap<PhieuNhapDTO, PHIEUNHAP>();
                phieuEF = Mapper.Map<PhieuNhapDTO, PHIEUNHAP>(phieuNhap);

                context.AddToPhieuNhapList(phieuEF);
                context.SaveChanges();

                //select id phieu nhap
                int phieuNhapID = (from phieuNhapItem in context.PhieuNhapList
                                   select phieuNhapItem.IDPhieuNhap).Max();

                return phieuNhapID;
            }
            catch {
                return 0;
            }            
        }
    }
}
